package com.project.web.admin.controller.common;

import com.project.model.core.Admin;
import com.project.model.core.Area;
import com.project.web.admin.service.core.AdminService;
import com.project.web.admin.service.core.AreaService;
import com.project.web.admin.service.core.MenuService;
import com.project.web.admin.utils.shiro.Principal;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 后台公用controller
 */
@Controller("adminCommonController")
@RequestMapping("/admin/common")
public class CommonController implements ServletContextAware, Serializable {

    private static final long serialVersionUID = -7624305021416504596L;

    @Resource(name = "adminServiceImpl")
    private AdminService adminService;

    @Resource(name = "menuServiceImpl")
    private MenuService menuService;

    private ServletContext servletContext;

    @Resource(name = "redisCaptchaService")
    private com.octo.captcha.service.CaptchaService imageCaptchaService;

    @Resource(name = "areaServiceImpl")
    private AreaService areaService;

       /**
     * 登录页面[同步方式下shiro登录]
     *
     * @return login.ftl
     */
    @RequestMapping(value = "/login" )
    public String login() {
        return "/admin/common/login.ftl";
    }

    /**
     * 登录页面[同步方式下shiro登录]
     *
     * @return login.ftl
     */
    @RequestMapping(value = "/login1" )
    @ResponseBody
    public String login1() {
//        // 从SecurityUtils里边创建一个 subject
//        Subject subject = SecurityUtils.getSubject();
//        // 在认证提交前准备 token（令牌）
//        AuthenticationToken token = new AuthenticationToken("", "",false,"","","");
//        // 执行认证登陆
//        subject.login(token);
        return "";
    }


    /**
     * 进入后台
     *
     * @return
     */
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String main(Model model) {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            Principal principal = new Principal();
            try {
                BeanUtils.copyProperties(principal,subject.getPrincipal());
            } catch (Exception e) {
                System.out.println("权限对象转化错误");
            }
            if (principal != null) {
                Admin admin = adminService.getById(principal.getId());
                model.addAttribute("admin", admin);
                model.addAttribute("menuList", menuService.findOrdinaryTreeMenu(1, admin.getId()));
            }
        }
        return "/admin/common/main.ftl";
    }

    /**
     * 错误页面
     *
     * @return
     */
    @RequestMapping(value = "/error")
    public String error() {
        return "/admin/common/error.ftl";
    }

    /**
     * 权限错误
     */
    @RequestMapping("/unauthorized")
    public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
            response.addHeader("loginStatus", "unauthorized");
            try {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        return "/admin/config/unauth.ftl";
    }

    /**
     * 404
     */
    @RequestMapping("/resource_not_found")
    public String resourceNotFount() {
        return "/admin/common/resource_not_found.ftl";
    }

    /**
     * 验证码
     *
     * @param captchaId
     * @param request
     * @param response
     */
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void captcha(String captchaId, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(captchaId)) {
            captchaId = request.getSession().getId();
        }
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            BufferedImage bufferImage = (BufferedImage) imageCaptchaService.getChallengeForID(captchaId);
            ImageIO.write(bufferImage, "jpg", out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(out);
        }

    }

    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    /**
     * 返回省集合 - 异步
     */
    @ResponseBody
    @RequestMapping(value = "/json/localProvince", method = RequestMethod.GET)
    public List<Area> localProvince() {
        return areaService.findOnlyRoots();
    }

    /**
     * 返回市/区/县集合 - 异步
     */
    @ResponseBody
    @RequestMapping(value = "/json/localChildren", method = RequestMethod.GET)
    public List<Area> localChildren(Long id) {
        if (id == null) {
            return new ArrayList<>();
        } else {
            List<Area> childrenNode = areaService.findChildrenRootNodes(id);
            if (CollectionUtils.isNotEmpty(childrenNode)) {
                return childrenNode;
            } else {
                return areaService.findOnlyRoots();
            }
        }
    }
}
